//
//  ZPStatusOriginalView.swift
//  ZPWeibo
//
//  Created by zhangpeng on 16/4/19.
//  Copyright © 2016年 zhangpeng. All rights reserved.
//

import UIKit
import SnapKit
class ZPStatusOriginalView: UIView {

    var originalViewBottomConstraint: Constraint?
    
    //给控件赋值
    var status:ZPStatus!{
    
        didSet{
        
            //头像
            headImageView.sd_setImageWithURL(NSURL(string: status?.user?.profile_image_url ?? ""), placeholderImage: UIImage(named: "avatar_default_big"))
            //昵称
            nameLabel.text = status?.user?.screen_name
           // print("nameLabel.text")
            //会员等级
            mbrankImageView.image = getmbrankImage(status?.user?.mbrank ?? 0)
            
            
            // 时间(后期处理)
            timeLabel.text = getWeiboTimeString(status!.created_at!)
            
            // 来自(后期处理)
            sourceLabel.attributedText = getSourceString(status.source)
            
            // 认证
            verifiedImageView.image = getverifiedImage(status?.user?.verified_type ?? -1)
            
              // 微博正文
            contentLabel.text = status?.text
            
            // 先卸载掉原创微博底部约束
            self.originalViewBottomConstraint?.uninstall()
            
            /*
            是否有配图逻辑
            - status?.pic_urls.count != 0 ==  代表有配图
            - status?.pic_urls.count == 0 ==  代表没有配图
            */
            // 有配图
            
            if status?.pic_urls?.count != 0{
            
                //给我们的配图赋值
                pictureView.pictureInfo = status?.pic_urls
                
                //设置约束
                self.snp_makeConstraints(closure: { (make) -> Void in
                    self.originalViewBottomConstraint = make.bottom.equalTo(pictureView.snp_bottom).offset(10).constraint
                })
                
                //显示配图
                pictureView.hidden = false
            }else{
            
                // 没有配图
                // 原创微博的底部 == 微博正文底部 + 10
                self.snp_makeConstraints(closure: { (make) -> Void in
                    self.originalViewBottomConstraint = make.bottom.equalTo(contentLabel.snp_bottom).offset(10).constraint
                })
                
                //不显示配图
                pictureView.hidden = true
            }
            
            
        }
    }
    
    /// 处理微博时间逻辑
    //Fri Apr 22 17:15:54 +0800 2016
    /*
    - 微博时间字符串处理
    - 业务需求逻辑
    - 如果是今年
    - 如果是今天
    - 如果 < 60 s  显示格式: 刚刚
    - 如果 >=60 && < 60 * 60  显示格式: xx分钟前
    - 其他 显示格式: xx小时前
    - 如果是昨天
    -例如 2016-04-22 19:19:19  显示格式: 昨天 19:19
    - 其他
    -例如 2016-04-04 20:20:20  显示格式: 04月04日 20:20
    - 如果不是今年
    -例如: 2015-01-01 18:18:18 显示格式: 2015年01月01日 18:18
    */

    
    func getWeiboTimeString(weiboTime:String) -> String{
    
        
        let times = NSDateFormatter()
        // 设置格式
        // Fri Apr 22 17:15:54 +0800 2016
        times.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        // 设置locale(需要程序员设置 如果不设置的话 可能在真机时间不对)
        times.locale = NSLocale(localeIdentifier: "en_US")
        // 获得微博date
        let weiboDate = times.dateFromString(weiboTime)!
        
        let isThisYear = false
        // 代表是今年
        if isThisYear{
        
        }else{
        
            // 代表不是今年
            // 2015年01月01日 18:18
            times.dateFormat = "yyyy-MM-dd HH:mm"
            
            return times.stringFromDate(weiboDate)
        }
        
       // return ""
    }
    
    //判断是否是今年
    
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        
        fatalError("init(coder:) has not been implemented")
    }
    
     // 处理微博来源字符串
    func getSourceString(source:String?) ->NSMutableAttributedString{
    
        // 判断我们的来源字符串是否存在 且包含'\">'符号
        guard let s = source where s.containsString("\">") else{
        
            return NSMutableAttributedString(string: "")
        }
        let startRange = s.rangeOfString("\">")!
        
        let endRange = s.rangeOfString("</a")!
        
        let result = s.substringWithRange(startRange.endIndex..<endRange.startIndex)
        
         // 拼接后最终显示的结果
        let name = "来自\(result)"
        
        //为了更改部分属性，所以通过副本
        let attr = NSMutableAttributedString(string: name)
        
        // 转name 为NSString 然后获取nsrange
        
        let range = (name as NSString).rangeOfString("来自")
        
        // 通过富文本更改指定位置的属性
        attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGrayColor(), range: range)
        
        return attr
    }
    
    // 通过服务器返回来的int 数据 创建UIImage
    ///// 会员等级 0-6
    func getmbrankImage(mbrank:Int)->UIImage?{
    
        if mbrank > 0 && mbrank < 7{
        return UIImage(named: "common_icon_membership_level\(mbrank)")
            
        }else{
        
            return UIImage(named: "common_icon_membership_expired")
        }
    }
    
    // 认证图片逻辑处理
    /// 认证类型，-1：没有认证，0，认证用户，2,3,5: 企业认证，220: 达人
    
    func getverifiedImage(verified:Int)->UIImage?{
    
        switch verified{
        
        case 0:
            return UIImage(named: "avatar_vip")
        case 2,3,5:
            return UIImage(named: "avatar_enterprise_vip")
        case 220:
            return UIImage(named: "avatar_grassroot")
            
        default:
            return nil
        }
    }
    
      // MARK: - 设置视图
    private func setupUI(){
    
     // self.backgroundColor = RandomColor()
        
        addSubview(headImageView)
        addSubview(nameLabel)
        addSubview(timeLabel)
        addSubview(mbrankImageView)
        addSubview(sourceLabel)
        addSubview(verifiedImageView)
        addSubview(contentLabel)
        addSubview(pictureView)
        
        headImageView.snp_makeConstraints { (make) -> Void in
            
            
            make.top.leading.equalTo(10)
            
             make.size.equalTo(CGSize(width: 35, height: 35))
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(headImageView)
        
            make.leading.equalTo(headImageView.snp_trailing).offset(10)
        }
        
        
        // 03
        mbrankImageView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(nameLabel.snp_trailing).offset(10)
            make.centerY.equalTo(nameLabel)
        }
        
        // 04
        timeLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(nameLabel)
            make.bottom.equalTo(headImageView)
        }
        
        // 05
        sourceLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(timeLabel.snp_trailing).offset(10)
            make.bottom.equalTo(timeLabel)
        }
        
        // 06
        verifiedImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(headImageView.snp_trailing)
            make.centerY.equalTo(headImageView.snp_bottom)
        }
        
        // 07
        contentLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(headImageView.snp_bottom).offset(10)
            make.leading.equalTo(headImageView)
            make.width.equalTo(SCREENW - 20)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            
            // 已经在pictureView做完了
            // make.size.equalTo(CGSize(width: 100, height: 100))
            make.top.equalTo(contentLabel.snp_bottom).offset(10)
            make.leading.equalTo(contentLabel)
        }
        
        //原创微博设置约束
        self.snp_makeConstraints { (make) -> Void in
            self.originalViewBottomConstraint = make.bottom.equalTo(pictureView).offset(10).constraint
        }
    }
    
    // MARK: - 懒加载控件
    //用户头像
    private lazy var headImageView:UIImageView = UIImageView(image: UIImage(named: "avatar_default_big"))
    
    //用户昵称
      private lazy var nameLabel:UILabel = UILabel(textColor: UIColor.darkGrayColor(), textFont: 14)

    
    //会员等级
    private lazy var mbrankImageView :UIImageView = UIImageView(image: UIImage(named: "common_icon_membership"))
    
    //发表时间
    private lazy var timeLabel:UILabel = UILabel(textColor: ThemeColor, textFont: 10)
    
    //来自出处
    private lazy var sourceLabel:UILabel = UILabel(textColor: ThemeColor, textFont: 10)
    
    //认证
    private lazy var verifiedImageView:UIImageView = UIImageView(image: UIImage(named: "avatar_vgirl"))
    
    //微博正文
    
    private lazy var contentLabel:UILabel = {
    
        let lab = UILabel(textColor: UIColor.blackColor(), textFont: 14)

        lab.numberOfLines = 0
        
       // lab.text = "微博正文微博正文微博正文微博正文微博正文微博正文微博正文微博正文微博正文"
        
        return lab

    }()
    
    //微博配图
    
    private lazy var pictureView:ZPStatusPictureView = ZPStatusPictureView()
}
